home *** CD-ROM | disk | FTP | other *** search
/ Amiga Format CD 43 / Amiga Format CD43 (1999)(Future Publishing)(GB)(Track 1 of 2)[!][issue 1999-09].iso / -serious- / programming / other / python-1.52 / lib / python1.5 / getopt.py < prev    next >
Text File  |  1999-06-14  |  4KB  |  122 lines

  1. """Module getopt -- Parser for command line options.
  2.  
  3. This module helps scripts to parse the command line arguments in
  4. sys.argv.  It supports the same conventions as the Unix getopt()
  5. function (including the special meanings of arguments of the form `-'
  6. and `--').  Long options similar to those supported by GNU software
  7. may be used as well via an optional third argument.  This module
  8. provides a single function and an exception:
  9.  
  10. getopt() -- Parse command line options
  11. error    -- Exception (string) raised when bad options are found
  12. """
  13.  
  14. # Long option support added by Lars Wirzenius <liw@iki.fi>.
  15.  
  16. import string
  17.  
  18. error = 'getopt.error'
  19.  
  20. def getopt(args, shortopts, longopts = []):
  21.     """getopt(args, options[, long_options]) -> opts, args
  22.  
  23.     Parses command line options and parameter list.  args is the
  24.     argument list to be parsed, without the leading reference to the
  25.     running program.  Typically, this means "sys.argv[1:]".  shortopts
  26.     is the string of option letters that the script wants to
  27.     recognize, with options that require an argument followed by a
  28.     colon (i.e., the same format that Unix getopt() uses).  If
  29.     specified, longopts is a list of strings with the names of the
  30.     long options which should be supported.  The leading '--'
  31.     characters should not be included in the option name.  Options
  32.     which require an argument should be followed by an equal sign
  33.     ('=').
  34.  
  35.     The return value consists of two elements: the first is a list of
  36.     (option, value) pairs; the second is the list of program arguments
  37.     left after the option list was stripped (this is a trailing slice
  38.     of the first argument).  Each option-and-value pair returned has
  39.     the option as its first element, prefixed with a hyphen (e.g.,
  40.     '-x'), and the option argument as its second element, or an empty
  41.     string if the option has no argument.  The options occur in the
  42.     list in the same order in which they were found, thus allowing
  43.     multiple occurrences.  Long and short options may be mixed.
  44.  
  45.     """
  46.  
  47.     opts = []
  48.     if type(longopts) == type(""):
  49.         longopts = [longopts]
  50.     else:
  51.         longopts = list(longopts)
  52.     longopts.sort()
  53.     while args and args[0][:1] == '-' and args[0] != '-':
  54.         if args[0] == '--':
  55.             args = args[1:]
  56.             break
  57.         if args[0][:2] == '--':
  58.             opts, args = do_longs(opts, args[0][2:], longopts, args[1:])
  59.         else:
  60.             opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:])
  61.  
  62.     return opts, args
  63.  
  64. def do_longs(opts, opt, longopts, args):
  65.     try:
  66.         i = string.index(opt, '=')
  67.         opt, optarg = opt[:i], opt[i+1:]
  68.     except ValueError:
  69.         optarg = None
  70.  
  71.     has_arg, opt = long_has_args(opt, longopts)
  72.     if has_arg:
  73.         if optarg is None:
  74.             if not args:
  75.                 raise error, 'option --%s requires argument' % opt
  76.             optarg, args = args[0], args[1:]
  77.     elif optarg:
  78.         raise error, 'option --%s must not have an argument' % opt
  79.     opts.append(('--' + opt, optarg or ''))
  80.     return opts, args
  81.  
  82. # Return:
  83. #   has_arg?
  84. #   full option name
  85. def long_has_args(opt, longopts):
  86.     optlen = len(opt)
  87.     for i in range(len(longopts)):
  88.         x, y = longopts[i][:optlen], longopts[i][optlen:]
  89.         if opt != x:
  90.             continue
  91.         if y != '' and y != '=' and i+1 < len(longopts):
  92.             if opt == longopts[i+1][:optlen]:
  93.                 raise error, 'option --%s not a unique prefix' % opt
  94.         if longopts[i][-1:] in ('=', ):
  95.             return 1, longopts[i][:-1]
  96.         return 0, longopts[i]
  97.     raise error, 'option --' + opt + ' not recognized'
  98.  
  99. def do_shorts(opts, optstring, shortopts, args):
  100.     while optstring != '':
  101.         opt, optstring = optstring[0], optstring[1:]
  102.         if short_has_arg(opt, shortopts):
  103.             if optstring == '':
  104.                 if not args:
  105.                     raise error, 'option -%s requires argument' % opt
  106.                 optstring, args = args[0], args[1:]
  107.             optarg, optstring = optstring, ''
  108.         else:
  109.             optarg = ''
  110.         opts.append(('-' + opt, optarg))
  111.     return opts, args
  112.  
  113. def short_has_arg(opt, shortopts):
  114.     for i in range(len(shortopts)):
  115.         if opt == shortopts[i] != ':':
  116.             return shortopts[i+1:i+2] == ':'
  117.     raise error, 'option -%s not recognized' % opt
  118.  
  119. if __name__ == '__main__':
  120.     import sys
  121.     print getopt(sys.argv[1:], "a:b", ["alpha=", "beta"])
  122.